package com.scsj.supermarket.view.activity.bankcardmodel;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import com.scsj.supermarket.R;
import com.scsj.supermarket.base.QueryCardBase;
import com.scsj.supermarket.bean.QueryCardBean;
import com.scsj.supermarket.config.RxSPConfig;
import com.scsj.supermarket.customview.datepickers.ConvertUtils;
import com.scsj.supermarket.presenter.QueryCardPresenter;
import com.scsj.supermarket.utils.SkipUtils;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;
import com.vondear.rxtools.RxSPTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import es.dmoral.toasty.Toasty;


/**
 * 添加银行卡
 */
public class AddBankCardActivity extends BaseActivity implements View.OnClickListener, QueryCardBase.IView {

    /**
     * 杨**
     */
    private EditText mUserNameEt;
    /**  */
    private EditText mBankCardNumEdt;
    private EditText mBankSubBranchtv;
    /**  */
    private TextView mBankOfDepositTv;
    private ImageView mIcBankIv;
    /**
     * 下一步
     */
    private Button mNextBtn;
    //    private BankInfoBean bankinfobean;
    private String userName;
    private QueryCardPresenter presenter;
    private String cardNum = "";
    private String mSBankName;
    private String mSBankType;
    private String mSBankCardNum;
    private String mCardType;


    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_add_bank_card_layout);
        presenter = new QueryCardPresenter(this);
        initView();
        initListener();
        initData();
        //ScreenAdapterTools.getInstance().loadView((ViewGroup) getWindow().getDecorView());
        //ScreenAdapterTools.getInstance().reset(this);//如果希望android7.0分屏也适配的话,加上这句
        initToolbar();
        setToolbarTitle("添加银行卡");
        hasBack(true);
    }

    @Override
    protected void initView() {

        mUserNameEt = (EditText) findViewById(R.id.user_name_et);
        mBankCardNumEdt = (EditText) findViewById(R.id.Bank_card_num_edt);
        mBankSubBranchtv = (EditText) findViewById(R.id.bank_sub_branch_tv);
        mBankOfDepositTv = (TextView) findViewById(R.id.bank_of_deposit_tv);
        mIcBankIv = (ImageView) findViewById(R.id.ic_bank_iv);

        mNextBtn = (Button) findViewById(R.id.next_btn);

    }

    @Override
    protected void initListener() {
        mNextBtn.setOnClickListener(this);
        //监听银行卡密码变化
        mBankCardNumEdt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                Logger.d("beforeTextChanged==s==>"+s+"start==>"+start+"count==>"+count+"after==>"+after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                Logger.d("onTextChanged==s==>"+s+"start==>"+start+"count==>"+count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                String s1 = s.toString();
                if (s1 != null && checkBankCard(s1)) {
                    mSBankCardNum = s1;
                    mBankOfDepositTv.setVisibility(View.VISIBLE);
//                    bankinfobean = new BankInfoBean(s1);
                    presenter.deliverData(s1);
//                    mBankOfDepositTv.setText(bankinfobean.getBankName() + " " + bankinfobean.getCardType());
                    mIcBankIv.setVisibility(View.VISIBLE);
                } else {
                    mBankOfDepositTv.setVisibility(View.INVISIBLE);
                    mIcBankIv.setVisibility(View.INVISIBLE);
//                    Toast.makeText(MainActivity.this, "卡号 "+cardnum+" 不合法,请重新输入", Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    protected void initData() {

        userName = RxSPTool.getString(this, RxSPConfig.USER_TRUENAME);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.next_btn:
//                String mBankCardNum = mBankCardNumEdt.getText().toString().trim();
//                cardNum += mBankCardNum;
////                cardNum += "&cardBinCheck=true";
//                Logger.e("cardNum==>" + cardNum);
//                presenter.deliverData(cardNum);
                String mSUserName = mUserNameEt.getText().toString().trim();

//                mSBankName;mSBankCardNum
                String mSBankSubBranch = mBankSubBranchtv.getText().toString().trim();
                if(TextUtils.isEmpty(mSUserName)){
                    Toasty.info(this,"请输入您的姓名").show();
                    return;
                }
                if(TextUtils.isEmpty(mSBankCardNum) || TextUtils.isEmpty(mSBankName)){
                    Toasty.info(this,"请输入正确的银行卡号").show();
                    return;
                }
                if(TextUtils.isEmpty(mSBankSubBranch)){
                    Toasty.info(this,"请输入开户行").show();
                    return;
                }
                if(!"1".equals(mCardType) && !"2".equals(mCardType)){
                    Toasty.info(this,"暂时不支持此种银行卡类型").show();
                    return;
                }
                HashMap<String,String> map = new HashMap();
                map.put("name",mSUserName);
                map.put("cardNo",mSBankCardNum);
                map.put("bankOpen",mSBankSubBranch);
                map.put("bankName",mSBankName);
                map.put("cardType",mCardType);
                SkipUtils.toVerificationCard(this,map);
                break;
            default:
                break;
        }
    }

    /**
     * 校验过程：
     * 1、从卡号最后一位数字开始，逆向将奇数位(1、3、5等等)相加。
     * 2、从卡号最后一位数字开始，逆向将偶数位数字，先乘以2（如果乘积为两位数，将个位十位数字相加，即将其减去9），再求和。
     * 3、将奇数位总和加上偶数位总和，结果应该可以被10整除。
     * 校验银行卡卡号
     */
    public static boolean checkBankCard(String bankCard) {
        if (bankCard.length() < 15 || bankCard.length() > 19) {
            return false;
        }
        char bit = getBankCardCheckCode(bankCard.substring(0, bankCard.length() - 1));
        if (bit == 'N') {
            return false;
        }
        return bankCard.charAt(bankCard.length() - 1) == bit;
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhn 校验算法获得校验位
     *
     * @param nonCheckCodeBankCard
     * @return
     */
    public static char getBankCardCheckCode(String nonCheckCodeBankCard) {
        if (nonCheckCodeBankCard == null || nonCheckCodeBankCard.trim().length() == 0
                || !nonCheckCodeBankCard.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeBankCard.trim().toCharArray();
        int luhmSum = 0;
        for (int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if (j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char) ((10 - luhmSum % 10) + '0');
    }

    @Override
    public void showSuccessMsg(String s, QueryCardBean queryCardBean) {
        Logger.e("queryCardBean==>" + queryCardBean.toString());
        String bankJ = queryCardBean.getBank();
        String cardType = queryCardBean.getCardType();
        mSBankType = getSCardtype(cardType);
        AssetManager assetManager = this.getAssets();
        try {
            InputStream open = assetManager.open("BankCard.json");
            String BankCardStr = ConvertUtils.toString(open);
            JSONObject object = new JSONObject(BankCardStr);
            if (object.has(bankJ)) {
                mSBankName = object.optString(bankJ);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mBankOfDepositTv.setText(mSBankName + " " + mSBankType);
        String url = "https://apimg.alipay.com/combo.png?d=cashier&t=" + bankJ;
        Glide.with(this).load(url).into(mIcBankIv);

    }

    private String getSCardtype(String cardType) {
        if (!TextUtils.isEmpty(cardType)) {
            if ("DC".equals(cardType)) {
                mCardType = "1";
                return "储蓄卡";
            } else if ("CC".equals(cardType)) {
                mCardType = "2";
                return "信用卡";
            } else if ("SCC".equals(cardType)) {
                mCardType = "3";
                return "准贷记卡";
            } else if ("PC".equals(cardType)) {
                mCardType = "4";
                return "预付费卡";
            } else {
                mCardType = "0";
                return null;
            }

        } else {
            return null;
        }
    }

    @Override
    public void showErrorMsg(String s) {
        Logger.e("queryCardBean=error=>" + s);
    }



}
